package hashLinkGraph;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import mapred.util.Bytes;

public class ID implements Comparable<ID> {

	private long host;
	
	private long page;
	
	public ID(byte[] bs) {
		host = Bytes.Bytes2Long(Arrays.copyOfRange(bs, 0, 8));
		page = Bytes.Bytes2Long(Arrays.copyOfRange(bs, 8, 16));
	}
	
	public ID(String url) {
		String[] sp = (url.contains("://") ? splitUrl(url) : new String[]{ url, url });
		host = Bytes.Bytes2Long(hash(sp[0]));
		page = Bytes.Bytes2Long(hash(sp[1]));
	}
	
	private static byte[] hash(String text) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] ret = md.digest(text.getBytes());
			return Arrays.copyOfRange(ret, 0, 8);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private static String[] splitUrl(String url) {
		String[] ret = new String[2];
		int pos = url.indexOf("/", url.indexOf("://") + 3);
		if (pos < 0) {
			ret[0] = url;
			ret[1] = "";
		} else {
			ret[0] = url.substring(0, pos);
			ret[1] = url.substring(pos + 1);
		}
		return ret;
	}
	
	public long getHost() {
		return host;
	}
	
	public long getPage() {
		return page;
	}

	public byte[] toBytes() {
		return Bytes.concat(Bytes.Long2Bytes(host), Bytes.Long2Bytes(page));
	}
	
	public byte[] toHost() {
		return Bytes.Long2Bytes(host);
	}
	
	public String toString() {
		return Bytes.Bytes2Hex(this.toBytes());
	}

	@Override
	public int compareTo(ID other) {
		if (this.host == other.host) {
			return Long.valueOf(this.page).compareTo(other.page);
		} else {
			return Long.valueOf(this.host).compareTo(other.host);
		}
	}
	
	
	
}
